package com.itheima.shop.util;

import java.security.MessageDigest;

/**
 * MD5算法
 * 在该项目中，用于将明文密码转成暗文密码的算法
 */
public final class Md5Util {	
	private Md5Util(){}
	/**
	 * 将明文密码转成暗文密码
	 * @param password 明文密码
	 * @return String 暗文密码 32位16进制字符串的MD5算法
	 */
	public static String encodeByMd5(String password) throws Exception{
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] byteArray = md5.digest(password.getBytes());
		return byteArrayToHexString(byteArray);
	}
	/**
	 * 将byteArray转成16进制字符串
	 */
	private static String byteArrayToHexString(byte[] byteArray) {
		StringBuffer sb = new StringBuffer();
		for(byte b : byteArray){
			String hexString = byteToHexString(b);
			sb.append(hexString);
		}
		return sb.toString();
	}
	/**
	 * 将byte转成16进制字符串
	 * -31 E1
	 * 10  0A
	 */
	private static String[] hex = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	private static String byteToHexString(byte b) {
		int n = b;
		n=n<0?n+256:n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hex[d1] + hex[d2];
	}
}
